//
//  MainViewController.m
//  USB_Reader
//
//  Created by xiaozao on 15/3/21.
//  Copyright (c) 2015年 Tony_Wang. All rights reserved.
//


#import "MainViewController.h"
#import "SBookViewController.h"
#import <QuickLook/QuickLook.h>
#import "MyCollectionViewCell.h"

@interface MainViewController () <UICollectionViewDelegate, UICollectionViewDataSource,QLPreviewControllerDataSource,QLPreviewControllerDelegate,QLPreviewItem, UIDocumentInteractionControllerDelegate>

@property (nonatomic, retain) UICollectionView *myCollectionView;
@property (nonatomic, retain) NSUserDefaults * userDefaults;

/// bookarray @[@{@"type":@"类型1",@"path":@"",@"books":@[@"book1",@"book2"]}]
@property (nonatomic, retain) NSMutableArray * bookArrays;
@property (nonatomic, retain) NSMutableArray *bookName;

@property (nonatomic, retain) UIDocumentInteractionController *docInteractionController;


- (NSMutableArray *) booksFromBundle;

@end

@implementation MainViewController





- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.tintColor = [UIColor blackColor];
    
    NSLog(@"%f,%f", self.view.frame.size.height, self.view.frame.size.width);
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    
    flowLayout.itemSize = CGSizeMake(80, 130);
    
    flowLayout.sectionInset = UIEdgeInsetsMake(20, 20, 30, 20);
    
    self.myCollectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:flowLayout];
    // 代理人
    _myCollectionView.dataSource = self;
    _myCollectionView.delegate = self;
    _myCollectionView.backgroundColor = [UIColor whiteColor];
    
    [_myCollectionView registerClass:[MyCollectionViewCell class] forCellWithReuseIdentifier:@"reuse"];
    
    [self.view addSubview:_myCollectionView];
    

    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(refresh)];

    [self iTunesData];
    
    [_myCollectionView reloadData];
    // 最新release
    [flowLayout release];
    [_myCollectionView release];
    
    // Do any additional setup after loading the view, typically from a nib.
}



- (NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)controller
{
    return 1;
}



- (void)viewWillAppear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = NO;
}

- (void)setupDocumentControllerWithURL:(NSURL *)url
{
    if (self.docInteractionController == nil)
    {
        self.docInteractionController = [UIDocumentInteractionController interactionControllerWithURL:url];
        self.docInteractionController.delegate = self;
    }
    else
    {
        self.docInteractionController.URL = url;
    }
}

- (void)iTunesData
{
    //    self.bookArrays = [self booksFromBundle];
    NSString *docsDir = [NSHomeDirectory() stringByAppendingPathComponent:  @"Documents"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSDirectoryEnumerator *dirEnum = [fileManager enumeratorAtPath:docsDir];
    NSString *fileName;
    NSInteger number = 0;
    NSMutableArray *tempArrs = [NSMutableArray array];
    NSMutableArray *tempNameArrs = [NSMutableArray array];
    while (fileName = [dirEnum nextObject]) {
        number++;
                NSLog(@"FielName : %@" , fileName);
                NSLog(@"FileFullPath : %@" , [docsDir stringByAppendingPathComponent:fileName]) ;
        NSString *tempArr = [docsDir stringByAppendingPathComponent:fileName];
        [tempNameArrs addObject:fileName];
//        NSLog(@"~~~~路径 %@", tempArr);
        [tempArrs addObject:tempArr];
//        NSLog(@"name个数______%ld", tempNameArrs.count);
//        NSLog(@"路径个数_________%ld", tempNameArrs.count);
    }
    
    self.bookName = tempNameArrs;
    self.bookArrays = tempArrs ;
}




//- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
//{
//    return 1;
//}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    MyCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    
    NSURL *fileURL= nil;
    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDir = [documentPaths objectAtIndex:0];
    NSString *path = [documentDir stringByAppendingPathComponent:[self.bookArrays objectAtIndex:indexPath.item]];
    fileURL = [NSURL fileURLWithPath:path];
    
    [self setupDocumentControllerWithURL:fileURL];
    cell.title.text = [self.bookName objectAtIndex:indexPath.item];
    NSInteger iconCount = [self.docInteractionController.icons count];
    if (iconCount > 0)
    {
        cell.logo.image = [self.docInteractionController.icons objectAtIndex:iconCount - 1];
    }
        return cell;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.bookName.count;
}

// push第二页面
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *name = [self.bookName objectAtIndex:indexPath.item];
    NSInteger lenth = [name length];
    NSString *lastStr = [name substringFromIndex:(lenth - 3)];
    NSLog(@"选择的名字 ++ %@", lastStr);

//    if ([lastStr isEqualToString:@"txt"] || [lastStr isEqualToString:@"TXT"]) {
//            NSString *path = [self.bookArrays objectAtIndex:indexPath.item];
//        SBookViewController *sBookVC = [[SBookViewController alloc] initWithTitle:@"小说" path:path];
//        [self.navigationController pushViewController:sBookVC animated:YES];
//    } else {
    QLPreviewController *previewController = [[QLPreviewController alloc] init];
    previewController.dataSource = self;
    previewController.delegate = self;
    // start previewing the document at the current section index
//        previewController.currentPreviewItem = indexPath.item;
    previewController.currentPreviewItemIndex = indexPath.item;
    self.tabBarController.tabBar.hidden = YES;
    [[self navigationController] pushViewController:previewController animated:YES];
//    }
    //	[self presentViewController:previewController animated:YES completion:nil];
}



#pragma mark - UIDocumentInteractionControllerDelegate

- (NSString *)applicationDocumentsDirectory
{
    return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}

- (UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)interactionController
{
    return self;
}


#pragma mark - QLPreviewControllerDataSource


- (void)previewControllerDidDismiss:(QLPreviewController *)controller
{
    // if the preview dismissed (done button touched), use this method to post-process previews
}

- (id)previewController:(QLPreviewController *)previewController previewItemAtIndex:(NSInteger)idx
{
//    [previewController.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"click.png"] forBarMetrics:UIBarMetricsDefault];
    
    NSURL *fileURL = nil;
    NSArray *arr = [_myCollectionView indexPathsForSelectedItems];
    NSIndexPath *selectedIndexPath = [arr objectAtIndex:0];
    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDir = [documentPaths objectAtIndex:0];
    NSString *path = [documentDir stringByAppendingPathComponent:[self.bookName objectAtIndex:selectedIndexPath.row]];
    fileURL = [NSURL fileURLWithPath:path];
    
    return fileURL;
}

- (void) refresh {
//    self.bookArrays = [self booksFromBundle];
    NSString *docsDir = [NSHomeDirectory() stringByAppendingPathComponent:  @"Documents"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSDirectoryEnumerator *dirEnum = [fileManager enumeratorAtPath:docsDir];
    NSString *fileName;
    NSInteger number = 0;
    NSMutableArray *tempArrs = [NSMutableArray array];
    NSMutableArray *tempNameArrs = [NSMutableArray array];
    while (fileName = [dirEnum nextObject]) {
        number++;
        //        NSLog(@"FielName : %@" , fileName);
        //        NSLog(@"FileFullPath : %@" , [docsDir stringByAppendingPathComponent:fileName]) ;
        NSString *tempArr = [docsDir stringByAppendingPathComponent:fileName];
        [tempNameArrs addObject:fileName];
//        NSLog(@"~~~~路径 %@", tempArr);
        [tempArrs addObject:tempArr];
//        NSLog(@"name个数______%ld", tempNameArrs.count);
//        NSLog(@"路径个数_________%ld", tempNameArrs.count);
    }

    self.bookName = tempNameArrs;
    self.bookArrays = tempArrs ;

    [self.myCollectionView reloadData];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
